package com.tanhua.manage.service;

import cn.hutool.core.date.DateTime;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.manage.pojo.Admin;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AdminMapper adminMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param verificationCode//验证码
     * @param uuid//获取验证码时uuid
     * @return
     */
    public String login(String username, String password, String verificationCode, String uuid) {
        String redisKey = "CHECK_CODE_" + verificationCode;
        boolean isNew = false;

        ///校验验证码
        String redisData = (String) this.redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.isEquals(verificationCode, redisData)) {
            return null;//验证码错误
        }
        //验证码在校验完成后，需要废弃
        this.redisTemplate.delete(redisKey);

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("verificationCode", verificationCode);
        Admin admin = this.adminMapper.selectOne(queryWrapper);

        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", admin.getId());

        //生成token
        String token = Jwts.builder()
                .setClaims(claims)//payload，存放数据的位置，不能放置敏感数据，如：密码等
                .compact();
        try {
            //发送用户登录成功的消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", admin.getId());
            msg.put("date", System.currentTimeMillis());
            this.rocketMQTemplate.convertAndSend("my-tanhua-manage-login", msg);
        } catch (MessagingException e) {
            log.error("发送消息失败！", e);
        }

        return token + "|" + isNew;
    }

    /*public  Boolean saveAdmin(Map<String ,String >param,String token){
      User user=

        Admin admin=new Admin();
        admin.setId(param.get());
    }*/
}
